//
//  AssetsGroup.swift
//  Media
//
//  Created by han on 2021/6/8.
//

import UIKit
import Photos
// 相册资源

enum AlbumContentType {
    case all
    case image
    case audio
    case video
}

enum AlbumSortType {
    case positive // 日期最新的内容排在后面
    case reverse // 日期最新的内容排在前面
}

class AssetsGroup: NSObject {
    init(assetCollection: PHAssetCollection, fetchAssetsOptions: PHFetchOptions? = nil) {
        self.assetCollection = assetCollection
        self.fetchResult = PHAsset.fetchAssets(in: assetCollection, options: fetchAssetsOptions)
        super.init()
    }
    
    private(set) var assetCollection: PHAssetCollection
    private(set) var fetchResult: PHFetchResult<PHAsset>
    
}
extension AssetsGroup {
    var name: String {
        NSLocalizedString(assetCollection.localizedTitle ?? "", comment: "")
    }
    
    var numberOfAssets: Int {
        fetchResult.count
    }

    var firstObject: PHAsset? {
        fetchResult.firstObject
    }
    
    func posterImage(size: CGSize) -> UIImage? {
        guard assetCollection.assetCollectionSubtype != .smartAlbumAllHidden else { return nil }
        
        guard let asset = fetchResult.firstObject else { return nil }
        
        let imageOptions = PHImageRequestOptions()
        imageOptions.isSynchronous = true // 同步
        imageOptions.resizeMode = .exact
        let scale = UIScreen.main.scale
        var resultImage: UIImage?
        AssetsManager.shared.cachingImageManager.requestImage(for: asset, targetSize: CGSize(width: size.width * scale, height: size.height * scale), contentMode: .aspectFill, options: imageOptions) { image , _ in
            resultImage = image
        }
        return resultImage
    }
    
    
    
}
